package com.chapter.sample.juc;

import lombok.Data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;


public class CompletableFutureNetMallDemo {
    static List<NetMall> list = Arrays.asList(
            new NetMall("jd"),
            new NetMall("pdd"),
            new NetMall("tmall"));

    public static List<String> getPriceByStep(List<NetMall> list, String productName) {

        List<String> collect = list.stream().map(netMall ->
                        String.format(productName + "in %s price is %.2f", netMall.getMallName(), netMall.calcPrice(productName)))
                .toList();
        return collect;
    }

    public static List<String> getPriceBySync(List<NetMall> list, String productName) {
        List<String> collect = list.stream().map(netMall -> CompletableFuture.supplyAsync(() -> String.format(productName + "in %s price is %.2f", netMall.getMallName(), netMall.calcPrice(productName))))
                .toList()
                .stream()
                .map(CompletableFuture::join)
                .toList();
        return collect;
    }

    public static void main(String[] args) {
        Long start = System.currentTimeMillis();
        System.out.println(getPriceByStep(CompletableFutureNetMallDemo.list, "mysql"));
        Long end = System.currentTimeMillis();
        System.out.println("" + (end - start));

        Long startSync = System.currentTimeMillis();
        System.out.println(getPriceBySync(CompletableFutureNetMallDemo.list, "mysql"));
        Long endSync = System.currentTimeMillis();
        System.out.println("" + (endSync - startSync));
    }
}

@Data
class NetMall {

    private String mallName;

    public NetMall(String mallName) {
        this.mallName = mallName;
    }

    public double calcPrice(String productName) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }
}
